<?php
declare (strict_types = 1);

namespace app\api\controller;
use app\model\OrderReviewsModel;
use app\model\OrdersModel;
use app\model\ProductsModel;
use app\model\UserModel;
use think\App;
use think\facade\Db;

class OrderReviews extends Base {

    private $orderReviewsModel;

    private $userModel;

    private $req;

    private $uid;

    private $tp = null;

    private $product_id;

    private $productsModel;

    private $orderType = "review_rating";

    private $page;

    private $limit = 10;


    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->req = request()->param();

        $this->tp = isset($this->req['tp']) ? $this->req['tp']  : null;

        $this->product_id = isset($this->req['product_id']) ? $this->req['product_id']  : "";

        $this->orderType = isset($this->req['orderType']) ? $this->req['orderType']  :  "review_rating";

        $this->page = isset($this->req['page']) ? $this->req['page']  : 1;

        $this->orderReviewsModel = new OrderReviewsModel();

        $this->orderModel = new OrdersModel();

        $this->userModel = new UserModel();

        $this->productsModel = new ProductsModel();

    }



    /*
     * 获取评价列表
     * */

    public function getList()
    {
        if(!$this->req["product_id"]){
            return $this->fail("商品Id不能为空");
        }

        $where=[];
        $where[] = ['product_id','=',$this->product_id];
        $where[] = ['p_review_id','=',0];
        $where[] = ['review_status','<>',-1];
        if(!empty($this->tp)){
            switch ($this->tp){
                case 1:
                    $where[] = ['review_rating','>=',4];
                    break;
                case 2:
                    $where[] = ['review_rating','<=',3];
                    $where[] = ['review_rating','>=',2];
                    break;
                case 3:
                    $where[] = ['review_rating','<=',1];
                    break;
            }
        }


        $list = $this->orderReviewsModel->getList($where,$this->page,$this->limit,"review_rating","DESC");

        $total = $this->orderReviewsModel->getTotal($where);

        return $this->succData($total,$list);
    }

    /*
        * 获取评价列表
        * */

    public function getUserReviewsList()
    {
        $this->uid = $this->isLogin();
        $where=[];
        $where[] = ['p_review_id','=',0];
        $where[] = ['uid','=',$this->uid];
        $where[] = ['review_status','<>',-1];

        $list = $this->orderReviewsModel->getList($where,$this->page,$this->limit,"created_at","DESC");

        $total = $this->orderReviewsModel->getTotal($where);

        return $this->succData($total,$list);
    }


    /*
     * 商品评价
     *
     * */
    public function publishComments(){
        $this->uid = $this->isLogin();
        if(!$this->req["order_id"]){
            return $this->fail("订单Id 不能为空");
        }

        if(!$this->req["review_rating"]){
            return $this->fail("请给商品打个分吧~");
        }

        if(!$this->req["review_content"]){
            return $this->fail("请评价下商品吧~");
        }

        if(substr($this->req["order_id"],0,1) == "L"){
            return $this->fail("联合订单不支持此操作，请在订单页操作");
        }

        if(!$this->orderModel->isUserOrder($this->uid,$this->req["order_id"])){
            return $this->fail("订单不存在");
        }

        $orderInfo = $this->orderModel->getInfo($this->req["order_id"]);

        if(!in_array($orderInfo["order_status"],[4,5])){
            return $this->fail("订单状态不允许评价");
        }


        $specIds = array_column($orderInfo["itemsList"],"spec_id");
        if(!in_array($this->req["spec_id"],$specIds)){
            return $this->fail("订单中不存在此商品");
        }

        $userInfo = $this->userModel->getUserInfoByUid($this->uid);
        $userBaseInfo = [
            'uid' => $userInfo["uid"],
            'username' => $userInfo["username"],
            'mobile' => $userInfo["mobile"],
            'gender' => $userInfo["gender"],
            'avatar' => $userInfo["avatar"],
        ];
        $productInfo=[];
        $specInfo=[];
        foreach ($orderInfo["itemsList"] as $item){
            if($item["spec_id"] == $this->req["spec_id"]){
                $productInfo["product_id"] = $item["product_snapshot"]["product_id"];
                $productInfo["product_name"] = $item["product_snapshot"]["product_name"];
                $productInfo["product_thumbnail"] = $item["product_snapshot"]["product_thumbnail"];
                $one =[];
                $one["spec_id"] = $item["spec_snapshot"]["spec_id"];
                $one["spec_name"] = $item["spec_snapshot"]["spec_name"];
                $specInfo[] = $one;
                break;
            }
        }

        if(isset($this->req["review_content"]) && !empty($this->req["review_content"])){
            $this->req["review_content"] = base64_encode($this->req["review_content"]);
        }

        //存储数据
        Db::startTrans();
        $orderReviewsRes = $this->orderReviewsModel->addOne([
            "uid"=>$this->uid,
            "order_id"=>$this->req["order_id"],
            "product_id"=> $productInfo["product_id"],
            "spec_id"=>$this->req["spec_id"],
            "product_info"=>json_encode($productInfo,256),
            "user_info"=>json_encode($userBaseInfo,256),
            "spec_info"=>json_encode($specInfo,256),
            "review_rating"=>$this->req["review_rating"],
            "review_content"=>$this->req["review_content"],
            "review_thumbnail"=> (isset($this->req["review_thumbnail"]) && is_array($this->req["review_thumbnail"])) ? json_encode($this->req["review_thumbnail"],256) : "",
            "review_status"=>1,
            "is_hide"=>isset($this->req["is_hide"]) ? $this->req["is_hide"] : 0,
            "p_review_id"=>isset($this->req["p_review_id"]) ? $this->req["p_review_id"] : 0,
        ]);

        $orderUpdateStatusRes = $this->orderModel->updateOrderStatus($this->req["order_id"],5);


        $incrProductReviewsNum = $this->productsModel->incrProductReviewsNum($productInfo["product_id"], 1);


        if($orderReviewsRes && $orderUpdateStatusRes && $incrProductReviewsNum){
            Db::commit();
            return $this->succ("发表成功");
        }else{
            Db::rollback();
            return $this->fail("发表失败");
        }
    }



    /*
    * 获取指定评论详情
    * */
    public function getInfo(){
        if(!$this->req["review_id"]){
            return $this->fail("评论Id不能为空");
        }

        $where =[];
        $where[] = ["review_id","=",$this->req["review_id"]];
        if($this->uid){
            $where[] = ['uid','=',$this->uid];
        }
        $where[] = ['review_status','<>',-1];


        if(!$this->orderReviewsModel->getTotal($where)){
            return $this->fail("评论不存在");
        }

        $res = $this->orderReviewsModel->getInfo($this->req["review_id"]);

        if($res){
            return $this->succ($res);
        }else{
            return $this->fail();
        }
    }



    /*
     * 删除评论
     * */
    public function delReview(){
        $this->uid = $this->isLogin();
        if(!$this->req["review_id"]){
            return $this->fail("评论Id不能为空");
        }

        $where =[];
        $where[] = ["review_id","=",$this->req["review_id"]];
        $where[] = ['uid','=',$this->uid];
        $where[] = ['review_status','<>',-1];


        if(!$this->orderReviewsModel->getTotal($where)){
            return $this->fail("评论不存在");
        }

        $res = $this->orderReviewsModel->updateOne($this->req["review_id"],["review_status"=>-1]);
        if($res){
            return $this->succ();
        }else{
            return $this->fail();
        }
    }

}
